/**
 * Copyright (C), 2015-2019, 山东桔灯行信息科技有限公司
 * FileName: PetroChinaVerifyCardUtil
 * Author:   chen
 * Date:     19-5-21 下午3:52
 * Description: 中石油验证卡号工具类
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.duochuang.verifycard.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 〈一句话功能简述〉<br>
 * 〈中石油验证卡号工具类〉
 *
 * @author chen
 * @create 19-5-21
 * @since 1.0.0
 */
@Slf4j
public class PetroChinaVerifyCardUtil {
    //微信登录中石油cookie  ASP.NET_SessionId=scgjvii34stvvaghmijosykl; RedisSessionCookiesId=554518e3-b2b9-4933-a954-b1b5106cd673
    private static String WC_COOKIE = "ASP.NET_SessionId=scgjvii34stvvaghmijosykl; RedisSessionCookiesId=554518e3-b2b9-4933-a954-b1b5106cd673";

    public static String verifyCard(String cardNo, String cookie) {
        String url = "http://wx.95504.net/Micro/MicroHandler.ashx";

        // 配置请求信息（请求时间）
        RequestConfig rc = RequestConfig.custom().setSocketTimeout(60000)
                .setConnectTimeout(60000).build();
        // 获取使用DefaultHttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = "";
        try {
            if (url != null) {
                // 创建HttpGet对象，将URL通过构造方法传入HttpGet对象
                HttpPost httpPost = new HttpPost(url);

                // 将配置好请求信息附加到http请求中
                httpPost.setConfig(rc);

                httpPost.setHeader("Connection", "keep-alive");
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.901.400 QQBrowser/9.0.2524.400");
                httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-us;q=0.6,en;q=0.5;q=0.4");

                // 获取cookie
                if (cookie == null) {
                    cookie = WC_COOKIE;
                }
                httpPost.addHeader("Cookie", cookie);

                String cardName = RandomStrUtil.getStringRandom(8);
                // 构建消息实体
                StringEntity se = new StringEntity("methodflag=SPhoneValidate&cardname=" + cardName + "&idtype=1&idnum=12&cardasn=" + cardNo, Charset.forName("UTF-8"));
                se.setContentEncoding("UTF-8");
                // 发送Json格式的数据请求
//	               se.setContentType("application/json");
                httpPost.setEntity(se);

                // 执行DefaultHttpClient对象的execute方法发送GET请求，通过CloseableHttpResponse接口的实例，可以获取服务器返回的信息
                CloseableHttpResponse response = httpclient.execute(httpPost);
                try {
                    // 得到返回对象
                    HttpEntity entity = response.getEntity();
                    System.out.println(response.getAllHeaders().clone().length);
                    for (Header h : response.getAllHeaders()) {
                        System.out.println(h);
                    }

                    System.out.println();
                    for (Header h : httpPost.getAllHeaders()) {
                        System.out.println(h);

                    }
                    if (entity != null) {
                        // 获取返回结果
                        result = EntityUtils.toString(entity, "utf-8");
                    }
                } finally {
                    // 关闭到客户端的连接
                    response.close();
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭http请求
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(result);
        if (result.indexOf("微信用户获取失败") >= 0 || !result.contains("status") || result.contains("Object moved")) {
            System.out.println("queryOilCardStatus__keepSession___微信用户获取失败");
            log.warn("queryOilCardStatus__keepSession___微信用户获取失败——需要更新cookie");
            return "微信用户获取失败";
        }
        return result;
    }

    public static String verifyCardRetMsg(String cardNo, String cookie){
        String result = verifyCard(cardNo, cookie);
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            result = jsonObject.getString("msg");
        } catch (JSONException e){
            log.error("中石油 验证卡号返回结果解析异常", e);
        }
        return result;
    }
}
